package com.miao.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miao.ucenter.mapper.XcUserMapper;
import com.miao.ucenter.mapper.XcUserRoleMapper;
import com.miao.ucenter.model.dto.AuthParamsDto;
import com.miao.ucenter.model.dto.XcUserExt;
import com.miao.ucenter.model.po.XcUser;
import com.miao.ucenter.model.po.XcUserRole;
import com.miao.ucenter.service.OuthService;
import com.miao.ucenter.service.WxCodeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

//微信方式验证方法
@Service("wx_authservice")
public class WechatAuthImpl implements OuthService, WxCodeService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private XcUserMapper userMapper;
    @Autowired
    private XcUserRoleMapper userRoleMapper;
    @Autowired
    private WechatAuthImpl proxy;

    @Override
    public XcUserExt excute(AuthParamsDto authParamsDto) {
        String username = authParamsDto.getUsername();
        XcUser xcUser = userMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }

    @Override
    public XcUser wxAuth(String code) {
        //根据code获取token
        Map<String, String> map = getToken(code);
        String access_token = map.get("access_token");
        String openid = map.get("openid");
        //获取用户信息
        Map<String, String> userInfo = getUserInfo(access_token, openid);
        //插入数据库
        XcUser xcUser = proxy.addUser(userInfo);

        return xcUser;
    }

    //获取令牌
    private Map<String, String> getToken(String code){
        //得到获取令牌的url
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String wxUrl_template = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        String wxUrl = String.format(wxUrl_template, "wx17655f8047b85150", "68918d65287802a19b1905cbda7eaa93", code);
        //远程调用获取token
        ResponseEntity<String> exchange = restTemplate.exchange(wxUrl, HttpMethod.POST, null, String.class);
        String result = exchange.getBody();
        //result是json，转化为map
        Map<String, String> map = JSON.parseObject(result, Map.class);
        return map;

    }

    //携带令牌访问得到用户信息
    private Map<String, String> getUserInfo(String token, String openid){
        String wxUrl_template = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        //请求微信地址
        String wxUrl = String.format(wxUrl_template, token,openid);

        ResponseEntity<String> exchange = restTemplate.exchange(wxUrl, HttpMethod.GET, null, String.class);
        String result = exchange.getBody();
        Map<String, String> map = JSON.parseObject(result, Map.class);
        return map;

    }

    //将用户信息保存到数据库
    @Transactional
    public XcUser addUser(Map<String, String> map){
        String unionid = map.get("unionid");
        String nickname = map.get("nickname");
        //unionid为用户唯一标识
        LambdaQueryWrapper<XcUser> xcUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xcUserLambdaQueryWrapper.eq(XcUser::getWxUnionid, unionid);
        XcUser xcUser = userMapper.selectOne(xcUserLambdaQueryWrapper);
        if(xcUser != null){//登陆过
            return xcUser;
        }
        //第一次登录
        xcUser = new XcUser();
        xcUser.setId(UUID.randomUUID().toString());
        xcUser.setUsername(unionid);
        xcUser.setPassword(unionid);
        xcUser.setWxUnionid(unionid);
        xcUser.setNickname(nickname);
        xcUser.setName(nickname);
        xcUser.setUtype("101001");//学生角色
        xcUser.setStatus("1");
        xcUser.setCreateTime(LocalDateTime.now());
        userMapper.insert(xcUser);
        //向关系表插入
        XcUserRole xcUserRole = new XcUserRole();
        xcUserRole.setId(UUID.randomUUID().toString());
        xcUserRole.setUserId(xcUser.getId());
        xcUserRole.setRoleId("17");
        xcUserRole.setCreateTime(LocalDateTime.now());
        userRoleMapper.insert(xcUserRole);

        return xcUser;



    }
}
